<template>
  <div class="coupon-management">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索优惠券名称/代码"
          @input="handleSearch"
        >
        <i class="fas fa-search"></i>
      </div>
      <div class="filters">
        <select v-model="typeFilter">
          <option value="">全部类型</option>
          <option value="percentage">折扣券</option>
          <option value="fixed">满减券</option>
        </select>
        <select v-model="statusFilter">
          <option value="">全部状态</option>
          <option value="active">生效中</option>
          <option value="inactive">未生效</option>
          <option value="expired">已过期</option>
        </select>
      </div>
      <button class="add-btn" @click="showAddModal = true">
        <i class="fas fa-plus"></i>
        创建优惠券
      </button>
    </div>

    <!-- 优惠券列表 -->
    <div class="coupon-grid">
      <div 
        v-for="coupon in filteredCoupons" 
        :key="coupon._id" 
        class="coupon-card"
        :class="{ expired: isExpired(coupon) }"
      >
        <div class="coupon-header">
          <div class="coupon-type" :class="coupon.type">
            {{ coupon.type === 'percentage' ? '折扣券' : '满减券' }}
          </div>
          <div class="coupon-status" :class="getCouponStatus(coupon)">
            {{ getCouponStatusText(coupon) }}
          </div>
        </div>
        
        <div class="coupon-body">
          <div class="coupon-value" :class="coupon.type">
            <template v-if="coupon.type === 'percentage'">
              {{ coupon.value }}
              <span class="unit">%</span>
              <span class="off">OFF</span>
            </template>
            <template v-else>
              <span class="currency">¥</span>
              {{ coupon.value }}
            </template>
          </div>
          
          <div class="coupon-info">
            <h3>{{ coupon.name }}</h3>
            <p>{{ coupon.description }}</p>
          </div>

          <div class="coupon-conditions">
            <div class="condition-item" v-if="coupon.minPurchase">
              <i class="fas fa-shopping-cart"></i>
              满 ¥{{ coupon.minPurchase }} 可用
            </div>
            <div class="condition-item">
              <i class="fas fa-clock"></i>
              {{ formatDate(coupon.startDate) }} - {{ formatDate(coupon.endDate) }}
            </div>
            <div class="condition-item" v-if="coupon.usageLimit">
              <i class="fas fa-users"></i>
              已领取 {{ coupon.usedCount }}/{{ coupon.usageLimit }}
            </div>
          </div>
        </div>

        <div class="coupon-footer">
          <button class="edit-btn" @click="handleEdit(coupon)">
            <i class="fas fa-edit"></i>
            编辑
          </button>
          <button 
            class="toggle-btn" 
            :class="coupon.status"
            @click="toggleStatus(coupon)"
          >
            <i :class="coupon.status === 'active' ? 'fas fa-pause' : 'fas fa-play'"></i>
            {{ coupon.status === 'active' ? '暂停' : '启用' }}
          </button>
          <button class="delete-btn" @click="handleDelete(coupon)">
            <i class="fas fa-trash"></i>
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      <span>第 {{ currentPage }} 页</span>
      <button 
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>

    <!-- 添加/编辑优惠券弹窗 -->
    <div class="modal" v-if="showAddModal || showEditModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑优惠券' : '创建优惠券' }}</h3>
          <button class="close-btn" @click="closeModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="handleSubmit">
            <div class="form-group">
              <label>优惠券名称</label>
              <input type="text" v-model="formData.name" required>
            </div>
            <div class="form-group">
              <label>优惠券描述</label>
              <textarea v-model="formData.description" rows="3"></textarea>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>优惠类型</label>
                <select v-model="formData.type" required>
                  <option value="percentage">折扣券</option>
                  <option value="fixed">满减券</option>
                </select>
              </div>
              <div class="form-group">
                <label>优惠值</label>
                <div class="input-with-unit">
                  <input 
                    type="number" 
                    v-model="formData.value" 
                    :min="formData.type === 'percentage' ? 1 : 0"
                    :max="formData.type === 'percentage' ? 100 : undefined"
                    step="0.01"
                    required
                  >
                  <span class="unit">{{ formData.type === 'percentage' ? '%' : '元' }}</span>
                </div>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>最低消费</label>
                <div class="input-with-unit">
                  <input type="number" v-model="formData.minPurchase" min="0" step="0.01">
                  <span class="unit">元</span>
                </div>
              </div>
              <div class="form-group">
                <label>发放限量</label>
                <input type="number" v-model="formData.usageLimit" min="0">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>开始时间</label>
                <input 
                  type="datetime-local" 
                  v-model="formData.startDate"
                  required
                >
              </div>
              <div class="form-group">
                <label>结束时间</label>
                <input 
                  type="datetime-local" 
                  v-model="formData.endDate"
                  :min="formData.startDate"
                  required
                >
              </div>
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="formData.status" required>
                <option value="active">生效</option>
                <option value="inactive">暂停</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="closeModal">取消</button>
              <button type="submit" class="submit-btn">
                {{ showEditModal ? '保存修改' : '创建优惠券' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { couponApi } from '@/api'
import type { Coupon } from '@/types'

// 状态变量
const coupons = ref<Coupon[]>([])
const searchQuery = ref('')
const typeFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const showAddModal = ref(false)
const showEditModal = ref(false)

// 表单数据
const formData = ref({
  name: '',
  description: '',
  type: 'percentage',
  value: 0,
  minPurchase: 0,
  usageLimit: 0,
  startDate: '',
  endDate: '',
  status: 'active'
})

// 过滤优惠券列表
const filteredCoupons = computed(() => {
  return coupons.value.filter(coupon => {
    const matchQuery = coupon.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                      coupon.code.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchType = !typeFilter.value || coupon.type === typeFilter.value
    const matchStatus = !statusFilter.value || getCouponStatus(coupon) === statusFilter.value
    return matchQuery && matchType && matchStatus
  })
})

// 判断优惠券是否过期
const isExpired = (coupon: Coupon) => {
  return new Date(coupon.endDate) < new Date()
}

// 获取优惠券状态
const getCouponStatus = (coupon: Coupon) => {
  if (isExpired(coupon)) return 'expired'
  if (new Date(coupon.startDate) > new Date()) return 'inactive'
  return coupon.status
}

// 获取优惠券状态文本
const getCouponStatusText = (coupon: Coupon) => {
  const status = getCouponStatus(coupon)
  const statusMap = {
    active: '生效中',
    inactive: '未生效',
    expired: '已过期'
  }
  return statusMap[status as keyof typeof statusMap]
}

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchCoupons()
}

// 编辑优惠券
const handleEdit = (coupon: Coupon) => {
  formData.value = {
    ...coupon,
    startDate: new Date(coupon.startDate).toISOString().slice(0, 16),
    endDate: new Date(coupon.endDate).toISOString().slice(0, 16)
  }
  showEditModal.value = true
}

// 切换优惠券状态
const toggleStatus = async (coupon: Coupon) => {
  const newStatus = coupon.status === 'active' ? 'inactive' : 'active'
  const message = newStatus === 'inactive' ? '暂停' : '启用'
  
  if (!confirm(`确定要${message}优惠券"${coupon.name}"吗？`)) return

  try {
    await couponApi.updateStatus(coupon._id, newStatus)
    const index = coupons.value.findIndex(c => c._id === coupon._id)
    if (index !== -1) {
      coupons.value[index].status = newStatus
    }
  } catch (error) {
    console.error('Failed to update coupon status:', error)
  }
}

// 删除优惠券
const handleDelete = async (coupon: Coupon) => {
  if (!confirm(`确定要删除优惠券"${coupon.name}"吗？此操作不可恢复。`)) return

  try {
    await couponApi.delete(coupon._id)
    coupons.value = coupons.value.filter(c => c._id !== coupon._id)
  } catch (error) {
    console.error('Failed to delete coupon:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (showEditModal.value) {
      await couponApi.update(formData.value._id, formData.value)
      const index = coupons.value.findIndex(c => c._id === formData.value._id)
      if (index !== -1) {
        coupons.value[index] = { ...coupons.value[index], ...formData.value }
      }
    } else {
      const response = await couponApi.create(formData.value)
      coupons.value.unshift(response.data)
    }
    closeModal()
  } catch (error) {
    console.error('Failed to save coupon:', error)
  }
}

// 关闭弹窗
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    name: '',
    description: '',
    type: 'percentage',
    value: 0,
    minPurchase: 0,
    usageLimit: 0,
    startDate: '',
    endDate: '',
    status: 'active'
  }
}

// 获取优惠券列表
const fetchCoupons = async () => {
  try {
    const response = await couponApi.getList({
      page: currentPage.value,
      type: typeFilter.value,
      status: statusFilter.value
    })
    coupons.value = response.data
    totalPages.value = Math.ceil(response.total / response.pageSize)
  } catch (error) {
    console.error('Failed to fetch coupons:', error)
  }
}

// 初始化
fetchCoupons()
</script>

<style scoped>
.coupon-management {
  padding: 24px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.search-box i {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.filters {
  display: flex;
  gap: 16px;
}

.filters select {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.add-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.coupon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.coupon-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
}

.coupon-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.coupon-card.expired {
  opacity: 0.6;
}

.coupon-header {
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.coupon-type {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.coupon-type.percentage {
  background: #f9f0ff;
  color: #722ed1;
}

.coupon-type.fixed {
  background: #e6f7ff;
  color: #1890ff;
}

.coupon-status {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.coupon-status.active {
  background: #f6ffed;
  color: #52c41a;
}

.coupon-status.inactive {
  background: #fff7e6;
  color: #faad14;
}

.coupon-status.expired {
  background: #fff1f0;
  color: #ff4d4f;
}

.coupon-body {
  padding: 24px;
}

.coupon-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 16px;
}

.coupon-value.percentage {
  color: #722ed1;
}

.coupon-value.fixed {
  color: #1890ff;
}

.coupon-value .unit {
  font-size: 20px;
  margin-left: 4px;
}

.coupon-value .off {
  font-size: 16px;
  margin-left: 8px;
  color: #999;
}

.coupon-value .currency {
  font-size: 20px;
  margin-right: 4px;
}

.coupon-info h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.coupon-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.coupon-conditions {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.condition-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 12px;
}

.condition-item i {
  color: #999;
}

.coupon-footer {
  padding: 12px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 8px;
}

.coupon-footer button {
  flex: 1;
  padding: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  font-size: 12px;
}

.edit-btn {
  background: #e6f7ff;
  color: #1890ff;
}

.toggle-btn.active {
  background: #fff1f0;
  color: #ff4d4f;
}

.toggle-btn.inactive {
  background: #f6ffed;
  color: #52c41a;
}

.delete-btn {
  background: #fff1f0;
  color: #ff4d4f;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.pagination button {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.pagination button:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  border: none;
  background: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #666;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.input-with-unit {
  position: relative;
}

.input-with-unit input {
  padding-right: 32px;
}

.input-with-unit .unit {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}

.submit-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}
</style> 